package cn.service.productService.ProductServiceImpl;

import cn.service.productService.SkuService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import entity.Result;
import entity.productEntity.Sku;
import mapper.productMapper.SkuMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 朱颢阳
 * @description
 * @time 2024/8/26 14:50
 */
@Service
public class SkuServiceImpl implements SkuService {
    @Resource
    SkuMapper mapper;

    @Override
    public  Result updatesku(String string) {
        JSONObject jsonObject=JSONObject.parseObject(string);
        JSONArray array = (JSONArray) jsonObject.get("tableData");
        List<Sku> sku=array.toJavaList(Sku.class);
        Integer id= (Integer) jsonObject.get("product_id");
        for (Sku sku1 : sku) {
            sku1.setProduct_id(id);
            if (mapper.selectByPrimaryKey(sku1.getSku_code())>0){
                //存在，更新
                if(mapper.updateByPrimaryKey(sku1)>0){

                }else{
                    return Result.failed(500,"sku同步失败！");
                }
            }else {
                //不存在，新增
                if(mapper.insertSelective(sku1)>0){

                }else{
                    return Result.failed(500,"sku同步失败！");
                }
            }
        }
        return Result.success("sku同步成功");
    }

    @Override
    public Result getsku(Integer id) {
        List<Sku> skus = mapper.selectByProduct_idSkus(id);
        JSONArray json = (JSONArray) JSONArray.toJSON(skus);
        return Result.success(200,json);
    }

    @Override
    public Result find(Integer sku_code) {
        if (mapper.find(sku_code)>0){
            //已存在
            return Result.failed(500,"sku_code已存在，不可重复！");
        }else {
            return Result.success();
        }
    }

}
